<template>
    <div class="app-container" v-loading="listLoading">
        <el-form ref="form" label-width="80px">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="项目名称">
                        <el-input v-model="queryParms.name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="手机号">
                        <el-input v-model="queryParms.phone"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="queryPage">搜索</el-button>
                    <el-button type="success" @click="showAddDialog" v-if="role==1">新增</el-button>
                </el-col>
               
            </el-row>

        </el-form>
       

        <el-table  :data="list" element-loading-text="Loading" border fit highlight-current-row>
            <el-table-column  label="项目名称">
                <template slot-scope="scope">
                    {{ scope.row.name }}
                </template>
            </el-table-column>
            <el-table-column label="LOGO" >
                <template slot-scope="scope">
                    <div class="imgdiv">
                        <img :src="scope.row.logo">
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="地理位置">
                <template slot-scope="scope">
                    {{ scope.row.address }}
                </template>
            </el-table-column>
            <el-table-column label="总设备数">
                <template slot-scope="scope">
                    {{ scope.row.device_info.total }}
                </template>
            </el-table-column>
            <el-table-column label="设备在线数">
                <template slot-scope="scope">
                    <span style="color: #37F67D">{{ scope.row.device_info.line }}</span>
                    
                </template>
            </el-table-column>
            <el-table-column label="设备离线数">
                <template slot-scope="scope" >
                    <span style="color: #FFB325;"> {{ scope.row.device_info.off }}</span>
                   
                </template>
            </el-table-column>
          
           
            <el-table-column  label="操作" width="200">
                <template slot-scope="scope">
                    <el-button type="text" @click="showDrawer(scope.row)">项目人员</el-button>
                    <el-button type="text" @click="showEditDialog(scope.row)" v-if="role==1">编辑</el-button>
                    <el-button type="text" @click="deleteItem(scope.row)" v-if="role==1">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        
        <el-pagination
            style="float: right;margin-top: 20px;"
            @current-change="changePage"
            background
            layout="prev, pager, next,jumper"
            :total="queryParms.total">
        </el-pagination>

        <el-dialog title="新增项目" :visible.sync="dialogFormVisible" height="600">
            <el-form :model="form">
                <el-form-item label="项目名称" :label-width="formLabelWidth">
                    <el-input v-model="form.name" autocomplete="off" placeholder="请输入项目名称"></el-input>
                </el-form-item>
                <el-form-item label="项目key" :label-width="formLabelWidth">
                    <el-input v-model="form.app_bd_key" autocomplete="off" placeholder="请输入项目key"></el-input>
                </el-form-item>
                <el-form-item label="LOGO" :label-width="formLabelWidth">
                    <div class="imgMainDiv" v-if="form.logo">
                        <img :src="form.logo">
                    </div>
                    <div class="upload_div">
                        <i class="el-icon-plus"></i>
                        <input type="file" accept="image/*" @change="changeFile($event,'logo')"/>
                    </div>
                </el-form-item>
                <el-form-item label="项目面貌图" :label-width="formLabelWidth">
                    <div class="imgMainDiv" v-if="form.face_img">
                        <img :src="form.face_img">
                    </div>
                    <div class="upload_div">
                        <i class="el-icon-plus"></i>
                        <input type="file" accept="image/*" @change="changeFile($event,'face_img')"/>
                    </div>
                   
                </el-form-item>
                <el-form-item label="数据来源" :label-width="formLabelWidth">
                    <el-radio-group v-model="form.data_from">
                       
                        <el-radio :label="1">设备</el-radio>
                        <el-radio :label="2">本地客户端 </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="地址" :label-width="formLabelWidth">
                    <el-input v-model="form.address" autocomplete="off" placeholder="请输入项目地址"></el-input>
                </el-form-item>

                <el-form-item label="框选位置" :label-width="formLabelWidth">
                    <div class="mapmain">
                        <div id="container"></div>
                        <div class="clear_btn" @click="clearMap">
                            <span>清除</span>
                        </div>
                    </div>
                   
                </el-form-item>

               
                <el-form-item label="项目简介" :label-width="formLabelWidth">
                    <el-input
                        type="textarea"
                        :rows="5"
                        resize="none"
                        placeholder="请输入内容"
                        v-model="form.intro">
                    </el-input>
                    <!-- <el-input v-model="form.intro" autocomplete="off" placeholder="请输入项目简介"></el-input> -->
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="sureForm">确 定</el-button>
            </div>
        </el-dialog>



        <el-drawer
            title="项目人员管理"
            :visible.sync="drawer"
            size="50%"
            direction="rtl">
            <div class="positondiv">
                <el-form ref="form" label-width="80px">
                    <el-row :gutter="20">
                        <el-col :span="14">
                            <el-button type="success" style="margin-bottom: 20px;" @click="showAddPositionDialog" v-if="role==1">新增</el-button>
                        </el-col>
                    </el-row>

                </el-form>
                <el-table  :data="userList" element-loading-text="Loading" border fit highlight-current-row>
                    <el-table-column  label="人员名称">
                        <template slot-scope="scope">
                            {{ scope.row.name }}
                        </template>
                    </el-table-column>
                   
                    <el-table-column  label="账号">
                        <template slot-scope="scope">
                            {{ scope.row.account }}
                        </template>
                    </el-table-column>
                    <el-table-column  label="手机">
                        <template slot-scope="scope">
                            {{ scope.row.phone }}
                        </template>
                    </el-table-column>
                    <el-table-column  label="角色">
                        <template slot-scope="scope">
                            {{ scope.row.role==1?'管理员':'项目成员' }}
                        </template>
                    </el-table-column>
                
                
                    <el-table-column  label="操作" width="200">
                        <template slot-scope="scope">
                        
                        
                            <el-button type="text" @click="deletePosition(scope.row)" v-if="role==1">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-drawer>



        <el-dialog title="人员授权" :visible.sync="dialogUserFormVisible">
            <el-form :model="posititonForm">

                <el-form-item label="选择人员" :label-width="formLabelWidth">
                    <el-select v-model="posititonForm.user_id" placeholder="请选择">
                        <el-option
                        v-for="item in userListTable"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
               
            
               
       
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogUserFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="surePostionForm">确 定</el-button>
            </div>
        </el-dialog>



        
    </div>
</template>

<script>
import homeapi from '@/api/tailings_monitoring_service_smos_api.js'
import until from '@/api/until.js'
import { mapGetters } from 'vuex'
export default {
    data() {
        return {
            list: null,
            listLoading: true,
            queryParms:{
                page:1,
                page_size:10,
                name:"",
                phone:"",
                total:0,
            },
            form:{
                app_bd_key:"",
                name:"",
                logo:"",
                intro:"",
                address:"",
                gps_lng:"",
                gps_lat:"",
                data_from:"1",
                face_img:"",
                gps_info:"",
            },
            dialogFormVisible:false,
            formLabelWidth:'100px',

            drawer:false,

            devicePositionList:[],
            nowItem:{},
            userList:[],
            userListTable:[],

            posititonForm:{
                app_id:"",
                user_id:"",
                role:"",
            },
            dialogUserFormVisible:false,
            app_id:"",
        }
    },
    computed: {
        ...mapGetters([
        'role',
        
        ])
    },
    created() {
        this.fetchData()
        this.getUserList();
    },
    methods: {
        changePage(page){
            this.queryParms.page=page;
            this.fetchData();
        },

        showAddPositionDialog(){
            this.dialogUserFormVisible=true;
            this.posititonForm={
                app_id:"",
                user_id:"",
                role:"",
            }

        },

        showDrawer(item){
            this.drawer=true;
            this.nowItem=item;
            this.getProjectUser();
        },

        //获取所有人员
        async getUserList(){
            let page=1;
            let page_size=99999
            let name=""
            let phone=""
            let data=await homeapi.Smos_apiUserPageGet({page,page_size,name,phone});
            if(data.error_code==0){
                this.userListTable=data.data.list?data.data.list:[];
            }
        },

        //获取项目下的人员
        async getProjectUser(){
            let app_id=this.nowItem.app_id
            let data=await homeapi.Smos_apiApp_userAllGet({app_id})
            if(data.error_code==0){
                this.userList=data.data.list;
            }

        },

        async fetchData() {
            let form=this.queryParms
            let data=await homeapi.Smos_apiAppPageGet(form);
            if(data.error_code==0){
                this.listLoading=false;
                this.list=data.data.list;
                this.queryParms.total=data.data.total
            }
        },
        queryPage(){
            this.queryParms.page=1;
            this.fetchData();
        },
        showAddDialog(){
            this.dialogFormVisible=true;
            this.form={
                app_bd_key:"",
                name:"",
                logo:"",
                intro:"",
                address:"",
                gps_lng:"",
                gps_lat:"",
                data_from:"1",
                face_img:"",
                gps_info:"",
            }
            this.$nextTick(()=>{
                this.createMap()
            })
        },
        async sureForm(){
            if(this.form.app_id){
                this.editForm();
            }
            else{
                this.addForm();
            }
        },
        async addForm(){
            let form=this.form;
            this.listLoading=true;
            let data=await homeapi.Smos_apiAppCreatePost(form);
            console.log(data)
            if(data.error_code==0){
                this.listLoading=false
                this.$message.success("新增成功")
                this.dialogFormVisible=false;
                this.fetchData()

            }
        },
        async editForm(){
            let form=this.form;
            this.listLoading=true;
            let data=await homeapi.Smos_apiAppUpgradePut(form);
            if(data.error_code==0){
                this.listLoading=false
                this.$message.success("编辑成功")
                this.dialogFormVisible=false;
                this.fetchData()

            }
        },
        showEditDialog(item){
            this.dialogFormVisible=true;
            this.form=item;
            this.$nextTick(()=>{
                this.createMap()
            })
          
        },
        async deleteItem(item){
            this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
             }).then(async () => {
                let app_id=item.app_id
                this.listLoading=true;
                let data=await homeapi.Smos_apiAppDeleteDelete({app_id});
                if(data.error_code==0){
                    this.listLoading=false;
                    this.$message.success("删除成功");
                    this.queryPage();
                }
            }).catch(() => {
                       
             });
        },
        async changeFile(e,type){
            
            let file=e.target.files[0];
            var formData = new FormData();
            // 服务端要求参数是 pic1 
            formData.append('image',file);
            console.log(formData)
            this.listLoading=true;
            let data=await homeapi.Smos_apiUpload_imgPost({},formData);
            if(data.error_code==0){
                this.listLoading=false
                this.form[type]=data.data
            }
        },
        async deletePosition(item){
            this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
             }).then(async () => {
                let app_id=this.nowItem.app_id
               
                let user_id=item.id
                this.listLoading=true;
                let data=await homeapi.Smos_apiApp_userDeleteDelete({app_id,user_id});
                if(data.error_code==0){
                    this.listLoading=false;
                    this.$message.success("删除成功");
                    this.getProjectUser();
                }
            }).catch(() => {
                       
            });
        },
        async surePostionForm(){
            let form=this.posititonForm
            form.app_id=this.nowItem.app_id
            this.userListTable.map(res=>{
                if(res.id==form.user_id){
                    form.role=res.role
                }
            })
            this.listLoading=true;
            let data=await homeapi.Smos_apiApp_userCreatePost(form);
            if(data.error_code==0){
                this.getProjectUser();
                this.listLoading=false;
                this.dialogUserFormVisible=false
            }
        },


        createMap(){
            let _this=this;
            window.AMapLoader.load({
                key: "4dcf7ff87677856989b63e34501cc00e", //申请好的Web端开发者 Key，调用 load 时必填
                version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
            }).then((AMap) => {
                
                this.map = new AMap.Map("container",{
                    center: [102.80, 25.004],
                    zoom:16,
                    layers:[
                        new AMap.TileLayer.RoadNet({
                            zIndex:12
                        }),
                        new AMap.TileLayer.Satellite()
                    ]
                });
               

              
                // this.map.on("click", this.clickListener);
                var autoOptions = {
                    input: "tipinput"
                };
                if(this.posititonForm.gps_lat && this.posititonForm.gps_lng){
                    this.maker=new AMap.Marker({
                        position: [this.posititonForm.gps_lng,this.posititonForm.gps_lat],
                        map: this.map
                    });
                }
                AMap.plugin(['AMap.MouseTool'], function(){
                    // var auto = new AMap.AutoComplete(autoOptions);
                    // console.log(auto)
                    // var placeSearch = new AMap.PlaceSearch({
                    //     map: _this.map
                    // });  //构造地点查询类
                    // auto.on("select", select);//注册监听，当选中某条记录时会触发
                    // function select(e) {
                    //     console.log(e)
                    //     placeSearch.setCity(e.poi.adcode);
                    //     placeSearch.search(e.poi.name);  //关键字查询查询
                    // }
                    var mouseTool = new AMap.MouseTool(_this.map)
                    var polygon=mouseTool.polygon({
                        strokeColor: "#FF33FF", 
                        strokeOpacity: 1,
                        strokeWeight: 6,
                        strokeOpacity: 0.2,
                        fillColor: '#1791fc',
                        fillOpacity: 0.4,
                        // 线样式还支持 'dashed'
                        strokeStyle: "solid",
                        // strokeStyle是dashed时有效
                        // strokeDasharray: [30,10],
                    })
                 
                    mouseTool.on('draw', function(event) {
                        // console.log(event.obj._opts.path)
                        _this.form.gps_info=JSON.stringify(event.obj._opts.path)
                        // event.obj 为绘制出来的覆盖物对象
                        console.log(event)
                    })


                    

                });
                if(_this.form.gps_info){
                    let gps_info=JSON.parse(_this.form.gps_info);
                    var polygonMain = new AMap.Polygon({
                        map: _this.map,
                        path: gps_info, // 多边形的点
                        strokeColor: "#FF33FF", 
                        strokeOpacity: 1,
                        strokeWeight: 6,
                        strokeOpacity: 0.2,
                        fillColor: '#1791fc',
                        fillOpacity: 0.4,
                        // 线样式还支持 'dashed'
                        strokeStyle: "solid",
                    });
                    var bounds = polygonMain.getBounds()
                    console.log(bounds)
              
                    var center = bounds.getCenter();
                    _this.map.setCenter(center); 
                }
            })
            .catch((e) => {
                console.error(e); //加载错误提示
            });
        },
        clearMap(){
            this.form.gps_info=""
            this.map.clearMap();
        }
    }
}
</script>
<style>
    .el-dialog__body{
        height: 700px !important;
        overflow: auto;
    }
</style>
<style lang="css" scoped>
    .upload_div{
        width: 160px;
        height: 160px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #ddd;
        border-radius: 8px;
        position: relative;
        float: left;
        margin-left: 10px;
        

    }
    .upload_div input{
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        width: 100%;
        height: 100%;
    }
    .imgdiv{
        width: 120px;
        
    }
    .imgdiv img{
        width: 100%;
       
    }
    .upload_div i{
        font-size: 32px;
    }
    .imgMainDiv{
        width: 160px;
        height: 160px;
        float: left;
    }
    .imgMainDiv img{
        width: 100%;
        height: 100%;
    }
    #container{
        width: 100%;
        height: 600px;
    }
    .mapmain{
        position: relative;
        width: 100%;

    }
    .clear_btn{
        position: absolute;
        width: 80px;
        height: 35px;
        background: #409EFF;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #ffffff;
        border-radius: 8px;
        top: 15px;
        left: 15px;
        cursor: pointer;
        z-index: 999;
    }
</style>